

<template>
  <div class="create-order">
    <s-header :name="'生成订单'" @callback="deleteLocal"></s-header>
    <!-- 地址 -->
    <div class="address-wrap">
      <div class="name" @click="goTo">
        <span>{{ showAddress.name }} </span>
        <span> | </span>
        <span>{{ showAddress.phone }}</span>
      </div>
      <div class="address">
        {{showAddress.detail}}
      </div>
      <van-icon class="arrow" name="arrow" />
    </div>
    <!-- 订货人信息 -->
    <van-field label="订货人手机号码" label-width="100px" v-model="buyerPhone" type="tel">
      <template #button>
        <van-button class="phone-btn" size="small" type="primary" @click="buyerPhone = showAddress.phone">填入收件人</van-button>
      </template>
    </van-field>
    <!-- 商品信息 -->
    <div class="good">
      <div class="good-item" v-for="(item) in orderStore.spec" :key="item.id">
        <div class="good-img"><img :src="item.imagePath" alt=""></div>
        <div class="good-desc">
          <div class="good-title">
            <span class="product-name">{{ item.productName }}</span>
            <div class="price">¥{{ item.price }}</div>
          </div>
          <div class="good-title">
            <span>{{ item.name }}</span>
            <span>x{{ item.count }}</span>
          </div>
          <div class="good-title" v-if="item.gift">
            <span>赠：{{ item.gift }}</span>
          </div>
          <div class="good-btn">
            <div class="price">¥{{ item.price }}</div>
          </div>
        </div>
      </div>
      <div class="good-charges" v-if="orderStore.charges.length>0">
        <nut-collapse>
          <nut-collapse-item name="name3">
            <template #title>收费附件</template>
            <template #value><div class="charges-price">{{chargeFee.toFixed(2)}}</div></template>
            <div class="charge-item" v-for="charge in orderStore.charges" :key="charge.id">
              <div class="charge-name">{{charge.name}}</div>
              <div class="charge-price">{{charge.price}}</div>
              <div class="charge-count">{{charge.count}}</div>
            </div>
          </nut-collapse-item>
        </nut-collapse>
      </div>
    </div>
    <!-- 送货上门 -->
    <van-cell-group v-if="canShip">
      <!-- 配送方式 -->
      <van-cell v-if="canShip" title="配送方式" value="送货上门" />
      <van-cell v-if="canSame" title="配送方式" value="快递邮寄" />
      <van-cell v-if="canTake" title="配送方式" value="自提" />
      <!-- 配送费 -->
      <van-cell title="配送费">
        {{isDistribution?showDeliveryAmount:'该地址不支持配送'}}
      </van-cell>
      <!-- 配送日期 -->
      <van-cell title="配送日期" @click="showDatePicker = true">
        {{showShipDateTime}}
      </van-cell>
      <van-popup v-model:show="showDatePicker" destroy-on-close position="bottom">
        <van-picker
            title="选择日期"
            :columns="dateColumns"
            @confirm="onDateConfirm"
            @cancel="onCancel"
        />
      </van-popup>
      <!-- 配送时间 -->
      <van-cell title="配送时间" @click="showTimePicker = true">
        {{shipTimeText || '请选择配送时间'}}
      </van-cell>
      <van-popup v-model:show="showTimePicker" destroy-on-close position="bottom">
        <van-picker
            title="选择时间"
            :columns="timeColumns"
            @confirm="onTimeConfirm"
            @cancel="onCancel"
        />
      </van-popup>
    </van-cell-group>
    <!-- 快递 -->
    <van-cell-group v-if="canSame">
      <!-- 配送方式 -->
      <van-cell title="配送方式" value="快递配送" />
      <!-- 配送费 -->
      <van-cell title="配送费">
        {{isDistribution?showDeliveryAmount:'该地址不支持配送'}}
      </van-cell>
      <!-- 配送时间 -->
      <van-cell title="配送时间">
        {{deliveryText }}
      </van-cell>
    </van-cell-group>
    <van-cell-group>
      <!-- 祝福语 -->
      <van-cell title="祝福语" v-if="false">
        <van-field v-model="greetingText" placeholder="请填写祝福语"></van-field>
      </van-cell>
      <!-- 备注 -->
      <van-cell title="备注">
        <van-field v-model="buyerMsg" rows="2" type="textarea" placeholder="请填写备注"></van-field>
      </van-cell>
    </van-cell-group>
    <!-- 占位 -->
    <div style="height: 140px;width: 100vw;opacity: 0;">222222222</div>
    <!-- 支付 -->
    <div class="pay-wrap">
      <div class="price">
        <span>商品金额</span>
        <span>¥{{ total }}</span>
      </div>
      <van-button @click="handleCreateOrder" class="pay-btn" type="primary" block>生成订单</van-button>
    </div>
    <van-popup
      closeable
      :close-on-click-overlay="false"
      v-model:show="state.showPay"
      position="bottom"
      :style="{ height: '30%' }"
      @close="close"
    >
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import {reactive, onMounted, computed, ref} from 'vue'
import sHeader from '@/components/SimpleHeader.vue'
import {fetchCreateOrder, fetchPayOrder, fetchRuleId} from '@/service/order'
import { setLocal} from '@/common/js/utils'
import {showLoadingToast, closeToast, showToast} from 'vant'
import { useRouter } from 'vue-router'
import {useAddress} from "@/stores/address";
import {useOrderStoreHook} from "@/stores/order";
import {fetchDistributionRule} from "@/service/distribution";
import dayjs from "dayjs";
const router = useRouter()
const state = reactive({
  address: {},
  showPay: false,
  orderNo: '',
  cartItemIds: []
})

//#region 地址
const { address, getSelectedAddress, getAddressList } = useAddress()
const showAddress = computed(() => {
  const data = getSelectedAddress()
  console.log('address',data)
  return {
    detail: data ? (data.province + data.city + data.area + data.addr) : '请选择收货地址',
    name: data? data.name:'-',
    phone: data? data.phone:'-',
  }
})
const getDeultAddress = async () => {
  await getAddressList()
  address.selectedId = address.selectedId || address.defaultId
  buyerPhone.value = showAddress.value.phone
}
// const toSelectAddress = () => {
//   router.push({
//     path: '/address',
//   })
// }
//#endregion

//#region 配送人信息
const buyerPhone = ref('')

//#endregion
  //#region 商品
  const orderStore = useOrderStoreHook()
  const chargeFee = computed(() => {
    let fee = 0
    orderStore.charges.forEach((item:any) => {
      fee = fee + item.price * item.count
    })
    return fee
  })
  //#endregion

onMounted(() => {
  init()
})

const init = async () => {
  showLoadingToast({ message: '加载中...', forbidClick: true });
  await getDeultAddress()
  await getDistribution()
  closeToast()
}

//#region 配送
const isDistribution = ref(false)
// 自提
const canTake = ref(false)
// 商家配送
const canShip = ref(false)
// 快递
const canSame = ref(false)
// 配送费用
const deliveryAmount = ref(0)
// 配送日期
const shipDate = ref('')
const showDatePicker = ref(false)
const showShipDateTime = computed(() => {
  if(!shipDate.value) return '请选择配送日期'
  return dayjs(shipDate.value).format('YYYY-MM-DD')
})
const validateDeliveryDates = ref<any[]>([])
const validateDeliveryTimes = ref<any[]>([])
const dateColumns = computed(() => {
  const columns:any[] = []
  validateDeliveryDates.value.forEach((item) => {
    columns.push({
      text: item.dateText,
      value: item.date,
    })
  })
  return columns
})
const onDateConfirm = ({selectedValues}) => {
  shipDate.value = selectedValues[0]
  validateDeliveryDates.value.forEach((item) => {
    if(item.date === selectedValues[0]) {
      validateDeliveryTimes.value = item.validateDeliveryTimes
      deliveryAmount.value = parseFloat(item.deliveryAmount)
    }
  })
  showDatePicker.value = false
}
//配送时间
const shipTimeText = ref('')
const showTimePicker = ref(false)
const timeColumns = computed(() => {
  const columns:any[] = []
  validateDeliveryTimes.value.forEach((item) => {
    columns.push({
      text: item,
      value: item,
    })
  })
  return columns
})
const onTimeConfirm = ({selectedValues}) => {
  shipTimeText.value = selectedValues[0]
  showTimePicker.value = false;
}

const onCancel = () => {
  showTimePicker.value = false
  showDatePicker.value = false
}

const showDeliveryAmount = computed(() => {
  if(deliveryAmount.value) return '￥' + deliveryAmount.value.toFixed(2)
  if(canShip) return '免配送费'
  if(canSame) return '包邮'
  return '无需配送费'
})
// 快递配送信息
const deliveryText = ref('')

const getDistribution = async () => {
  const data: any = getSelectedAddress()
  const skuids = orderStore.spec.map((item:any) => item.id).join(',')
  const quantitys = orderStore.spec.map((item:any) => item.count).join(',')
  const res = await fetchDistributionRule(data?.cityId, skuids, quantitys, data?.id)
  deliveryAmount.value = 0
  isDistribution.value = res.data.isDistribution != '0'
  canShip.value = res.data.canShip != '0'
  if(canShip.value) {
    // 分析配送时间, 选择配送时间后，确定deliveryAmount
    validateDeliveryDates.value = res.data.validateDeliveryDates
  }
  canSame.value = res.data.canSame != '0'
  if(canSame.value) {
    deliveryAmount.value = res.data.validateSameRow.reduce((cur: number, item:any) => cur + Number(item.deliveryAmount), 0)
    deliveryText.value = res.data.deliveryText
  }
}
//#endregion

//#region 祝福语
const greetingText = ref('')
//#endregion

//#region 备注
const buyerMsg = ref('')
//#endregion

const goTo = () => {
  router.push({ path: '/address', query: { cartItemIds: JSON.stringify(state.cartItemIds), from: 'create-order' }})
}

const deleteLocal = () => {
  setLocal('cartItemIds', '')
}

const handleCreateOrder = async () => {
  const addr = getSelectedAddress()
  if(!addr) {
    showToast('请选择地址')
    return
  }
  if(!buyerPhone.value) {
    showToast('请输入订货人手机号')
    return
  }
  let group:any = {}

  if(canShip.value) {
    if(!shipDate.value) {
      showToast('请选择配送日期')
      return
    }
    if(!shipTimeText.value) {
      showToast('请选择配送时间')
      return
    }
    group = {
      shipType: "delivery",
      shipDate: shipDate.value,
      shipTimeText: shipTimeText.value,
    }
  }
  if(canSame.value) {
    group = {
      shipType: "same",
    }
  }

  if(canTake.value) {
    // 不支持自提
    isDistribution.value = false
  }

  const data = await fetchRuleId(addr.cityId, orderStore.productId )
  const ruleIds = data.data[0].distribution_rule_id
  const params = {
    addr:{
      id: addr.id,
      name: addr.name,
      province: addr.province,
      city: addr.city,
      area: addr.area,
      addr: addr.addr,
      phone: addr.phone,
    },
    ruleIds,
    specIds: orderStore.spec.map((item:any) => item.id).join(','),
    quantitys: orderStore.spec.map((item:any) => item.count).join(','),
    chargeIds: orderStore.charges.map((item:any) => item.id).join(','),
    cquantitys: orderStore.charges.map((item:any) => item.count).join(','),
    deliveryAmount: deliveryAmount.value,
    buyerPhone: buyerPhone.value,
    cityId: addr.cityId,
    buyerMsg: buyerMsg.value,
    chargeExtend: JSON.stringify(orderStore.charges),
    group
  }
  const res = await fetchCreateOrder(params)
  toPayOrder(res.data.id)
}

const toPayOrder = async (id: string) => {
  const res = await fetchPayOrder(id)
  const url = res.data.url
  location.href = url
}

const close = () => {
  router.push({ path: '/order' })
}

const total = computed(() => {
  let sum = 0
  const productFee = orderStore.spec.reduce((cur, item:any) => {
    return cur + item.price * item.count
  }, 0)
  sum = chargeFee.value + productFee
  return sum
})
</script>

<style lang="less" scoped>
  @import '../common/style/mixin';
  .create-order {
    height: 100vh;
    overflow-y: auto;
    background: #f9f9f9;
    :deep(.van-field__label) {
      display: flex;
      align-items: center;
    }
    .address-wrap {
      margin-bottom: 20px;
      background: #fff;
      position: relative;
      font-size: 14px;
      padding: 15px;
      color: #222333;
      .name, .address {
        margin: 10px 0;
      }
      .arrow {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 20px;
      }
      &::before {
        position: absolute;
        right: 0;
        bottom: 0;
        left: 0;
        height: 2px;
        background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
        background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
        background-size: 80px;
        content: '';
      }
    }
    .good {
      background: #fff5f3;
      margin-bottom: 40px;
      --nut-collapse-wrapper-content-background-color: #fff5f3;
      --nut-collapse-wrapper-content-padding: 0 26px;
      :deep(.nut-collapse-item__title) {
        background: #fff5f3;
      }
    }
    .good-item {
      padding: 10px;
      display: flex;
      .good-img {
        img {
          .wh(100px, 100px)
        }
      }
      .good-desc {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 1;
        padding: 20px;
        .good-title {
          display: flex;
          justify-content: space-between;
          .product-name {
            font-size: 14px;
            font-weight: bold;
          }
          .price {
            font-size: 18px;
            color: red;
            margin-top: -10px;
          }
        }
        .good-btn {
          display: flex;
          justify-content: space-between;
          .van-icon-delete {
            font-size: 20px;
            margin-top: 4px;
          }
        }
      }
    }
    .charges-price {
      color: @primary;
      &::before {
        content: "￥";
        font-size: 14px;
      }
    }
    .good-charges {
      border-top: 1px solid #ccc;
      .charge-item {
        display: flex;
        justify-content: flex-end;
        margin: 10px 0;
        .charge-name {
          margin-right: auto;
        }
        .charge-price {
          margin-right: 10px;
          color: @primary;
          &::before {
            content: "￥";
            font-size: 12px;
          }
        }
        .charge-count {
          &::before {
            content: "x";
            font-size: 12px;
          }
        }
      }
    }
    .pay-wrap {
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      background: #fff;
      padding: 10px 0;
      padding-bottom: 50px;
      border-top: 1px solid #e9e9e9;
      >div {
        display: flex;
        justify-content: space-between;
        padding: 0 5%;
        margin: 10px 0;
        font-size: 14px;
        span:nth-child(2) {
          color: red;
          font-size: 18px;
        }
      }
      .pay-btn {
        background: @primary;
        position: fixed;
        bottom: 7px;
        right: 0;
        left: 0;
        width: 90%;
        margin: 0 auto;
      }
    }
    .phone-btn {
      background: @primary;
    }
  }
</style>
